package features.advance.jdk.dynamicproxy.jdk;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodType;

import static java.lang.invoke.MethodHandles.lookup;

/**
 * @author LIN
 * @date 2021-12-30 09:18
 */
public class MethodHandleTest {

    static class ClassA{

    }

    public static void main(String[] args) {
        try{
            MethodHandle printlnMH = getPrintlnMH(System.out);
            printlnMH.invokeExact("hello world");
        }catch(Exception e){
            e.printStackTrace();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
    }

    private static MethodHandle getPrintlnMH(Object receiver) throws NoSuchMethodException, IllegalAccessException {
        /**
         * lookup()方法来自于MethodHandles.lookup，这句的作用是在指定类中查找符合给定的方法名称、方法类型，
         * 并且符合调用权限的方法句柄
         */
        return lookup().findVirtual(receiver.getClass(),"println", MethodType.methodType(void.class,String.class)).bindTo(receiver);
    }
}
